<template>
  <div class="address-edit-page">
    <div class="tip">
      <p>1, 复制带有姓名,地址,电话的内容到智能识别上面的框里, 请用空格或者回车隔开</p>
      <p>2, 点击智能识别</p>
      <p>3, 点击保存/更新</p>
    </div>
    <ul class="form">
      <li>
        <span class="text">收件人姓名:</span>
        <span class="input">
          <cube-input v-model="postForm.nickname" placeholder="请输入收件人姓名" clearable :readonly="!isDone" class="close" />
        </span>
      </li>
      <li>
        <span class="text">收件人电话:</span>
        <span class="input">
          <cube-input v-model="postForm.mobile" placeholder="请输入收件电话号码" clearable :readonly="!isDone" class="close" />
        </span>
      </li>
      <li v-if="false">
        <span class="text">请选择地区:</span>
        <!-- 这里如果是编辑时,一定要判断city.addressIndex.length,否则子组件获取不到数据 -->
        <city-selector
          v-if="showCity"
          class="city"
          :class="{'active': city.cityActive}"
          :edit-selected="city.addressIndex"
          @citySelected="citySelected">
          <span style="color: #333">{{city.text}}</span>
        </city-selector>
      </li>
      <li>
        <span class="text">详细地址:</span>
        <span class="input info">
          <cube-textarea :force-expand="true" v-model="postForm.info" placeholder="请输入详细地址" :autofocus="$route.params.id > 0" :readonly="!isDone" class="close" />
        </span>
      </li>
      <li class="last">
        <span class="text">是否设为默认地址</span>
        <span class="input">
          <cube-switch v-model="postForm.isDefault" />
        </span>
      </li>
    </ul>
    <div class="auto">
      <cube-textarea v-model="autoStr" :autofocus="true" :auto-expand="true" :force-expand="true" placeholder="粘贴请有空格分隔, 格式: 姓名 电话 地址" />
      <cube-button class="autoBtn" @click="actionAuto">智能识别</cube-button>
    </div>
    <footer-button
      icon="cubeic-right"
      :text="buttonText"
      @submit="saveAddress"
    />
    <loading :show="loading" />
  </div>
</template>

<script>
import FooterButton from './components/FooterButton'
import CitySelector from './components/CitySelector'
import api from '@/api'
import Loading from '@/components/Loading'
export default {
  name: 'AddressEdit',
  components: {
    FooterButton,
    CitySelector,
    Loading
  },
  computed: {
    buttonText() {
      return this.$route.params.id && this.$route.params.id > 0 ? '更新' : '保存'
    },
    // edit => selected
    showCity() {
      if (this.$route.params.id > 0) {
        return this.city.addressIndex.length > 0
      } else {
        return true
      }
    }
  },
  watch: {
    showHeight() {
      if (this.docHeight > this.showHeight) {
        this.hideShow = false
      } else {
        this.hideShow = true
      }
    }
  },
  data() {
    return {
      postForm: {},
      city: {
        // selected
        addressIndex: [],
        text: '',
        cityActive: false,
        // selected id => db
        cityMap: []
      },
      loading: false,
      hideShow: false,
      // footer
      docHeight: document.documentElement.clientHeight || document.body.clientHeight,
      showHeight: document.documentElement.clientHeight || document.body.clientHeight,
      autoStr: '',
      isDone: false
    }
  },
  methods: {
    actionAuto() {
      // 广州市天河棠东东路御富科贸园128号 严庆 13632428223
      // 处理下顺序
      let str = this.autoStr.split(/\s/)
      // console.log(str)
      str = str.filter(x => x)
      if (str.length !== 3) {
        return this.$createToast({
          type: 'error',
          txt: '请填写完整, 或者用空格分隔开!'
        }).show()
      }
      const get = (arr) => {
        let tel
        let name
        let address
        if (/^1[3456789]\d{9}$/.test(arr[0])) {
          tel = arr[0]
          arr.splice(0, 1)
        } else if (/^1[3456789]\d{9}$/.test(arr[1])) {
          tel = arr[1]
          arr.splice(1, 1)
        } else if (/^1[3456789]\d{9}$/.test(arr[2])) {
          tel = arr[2]
          arr.splice(2, 1)
        } else {
          return []
        }
        if (arr[0].length >= 5) {
          name = arr[1]
          address = arr[0]
        } else {
          name = arr[0]
          address = arr[1]
        }
        return [name, tel, address]
      }

      const x = get(str)
      console.log(x)
      if (x.length === 0) {
        return this.$createToast({
          type: 'error',
          txt: '手机号错误'
        }).show()
      }

      this.postForm.nickname = x[0]
      this.postForm.mobile = x[1]
      this.postForm.info = x[2]
      // this.postForm.nickname = str[0]
      // this.postForm.mobile = str[1]
      // this.postForm.info = str[2]
      this.city.cityMap = ['666666', '666666', '666666']
      this.$createToast({
        type: 'none',
        txt: '识别成功,请点击保存或者更新'
      }).show()
      this.isDone = true
    },
    // CitySelector result
    citySelected(args) {
      const { selectedVal, selectedText } = args
      this.city.text = selectedText.join(', ')
      this.city.cityActive = true
      this.city.cityMap = selectedVal
    },
    // save
    saveAddress() {
      if (!this.postForm.nickname || !this.postForm.mobile || !this.postForm.info || this.city.cityMap.length === 0) {
        this.$createToast({
          type: 'error',
          txt: '请填写完整'
        }).show()
      } else if (!/^1[3456789]\d{9}$/.test(this.postForm.mobile)) {
        this.$createToast({
          type: 'error',
          txt: '手机号码错误'
        }).show()
      } else {
        const [provinceId, cityId, areaId] = this.city.cityMap
        // console.log(this.city.cityMap)
        this.loading = true
        api.Address.edit({
          id: this.$route.params.id,
          province_id: provinceId,
          city_id: cityId,
          area_id: areaId,
          // ...this.postForm,
          is_default: this.postForm.isDefault ? 1 : 0,
          mobile: this.postForm.mobile,
          nickname: this.postForm.nickname,
          address: this.postForm.info
        }).then(() => {
          this.$createToast({
            type: 'txt',
            txt: '操作成功',
            time: 500,
            onTimeout: () => {
              // order address
              // see views/order/components/Address.vue
              if (+this.$route.params.id === -2) {
                this.$router.back()
              } else {
                this.$router.push('/service/address-list')
              }
            }
          }).show()
        }).finally(() => {
          this.loading = false
        })
      }
    }
  },
  created () {
    // default user info
    const info = this.$store.getters['ExecUser/info']
    if (Object.keys(info).length > 0) {
      // 关闭默认 姓名与电话
      // this.postForm = Object.assign({}, { ...info, isDefault: true })
    }
    // edit default data
    if (this.$route.params.id && this.$route.params.id > 0) {
      this.isDone = true
      this.loading = true
      api.Address.view({ id: this.$route.params.id }).then(response => {
        const { data } = response
        this.postForm = Object.assign({}, {
          ...data,
          isDefault: data.is_default === '1',
          info: data.address
        })
        const { city } = data
        const selected = [city.province_id, city.city_id, city.area_id]
        this.city = {
          addressIndex: selected,
          text: `${city.province},${city.city},${city.area}`,
          cityMap: selected,
          cityActive: true
        }
      }).finally(() => {
        this.loading = false
      })
    }
  },
  mounted () {
    // key => fixed bug
    window.onresize = () => {
      return (() => {
        this.showHeight = document.documentElement.clientHeight || document.body.clientHeight
      })()
    }
  }
}
</script>

<style scoped lang="stylus">
.close
  background #f3f5f7
.tip
  padding 10px
  background white
  p
    text-align left
    //height 20px
    line-height 20px
.address-edit-page
  .form
    padding 10px
    li
      padding 10px
      span
        display block
        height 40px
        &.info
          height 50px
        &.text
          height 20px
          text-align left
          font-weight 700
          font-size 14px
      &.last
        // 解决遮住
        margin-top 20px

  // 地址选择器
  .city
    //background white
    //width 100%
    height 40px
    line-height 40px
    text-align left
    //padding-left 10px
    //border 0.5px solid #ebebeb
    color #d0d0d0
    box-sizing border-box
    &.active
      color red

  .auto
    padding-bottom 300px
    //background red
    .autoBtn
      margin-top 10px
</style>
